<template>
  <Dialog @ok="onReturnMedicine" title="待退药列表" :visible.sync="visible">
    <el-form :model="formModel" ref="form">
      <STable ref="table" :auto="false" :pagination="false" :data="list" :options="options" />
      <el-form-item label="退药备注：" :rules="[{ required: true, message: '请输入退药备注', trigger: 'blur' }]" style="margin-top: 10px" prop="remark">
        <el-input v-model="formModel.remark" placeholder="请输入退药备注" rows="4" type="textarea" />
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script>
import { hackParamsByArray } from "@utils/dataHandler";
export default {
  name: "RefundMedicine",
  data() {
    return {
      list: [],
      formModel: {
        remark: "",
        list: [],
      },
      options: [
        {
          width: "40px",
          dataIndex: "select",
          render: ({ row }) => <el-checkbox vModel={row.check} />,
        },
        {
          dataIndex: "drugName",
          title: "药品名称",
          render: ({ row }) => (
            <span style="cursor: pointer;" onClick={() => (row.check = !row.check)}>
              {row.drugName}
            </span>
          ),
        },
        {
          dataIndex: "batch",
          title: "批次号",
          render: ({ row }) => (
            <span style="cursor: pointer;" onClick={() => (row.check = !row.check)}>
              {row.batch}
            </span>
          ),
        },
        {
          title: "退药数量",
          render: ({ row, $index }) => (
            <el-form-item style="margin-top: 10px" rules={[{ validator: this.validator, trigger: "blur" }]} prop={`list.${$index}.count`}>
              <el-input
                onChange={(v) => (v ? !row.check && (row.check = true) : row.check && (row.check = false))}
                type="number"
                placeholder="请输入数量"
                vModel={row.count}
              >
                <span slot="append">{row.unitDesc}</span>
              </el-input>
            </el-form-item>
          ),
        },
      ],
      visible: false,
    };
  },
  methods: {
    validator(rule, value, callback) {
      callback(value ? (/^[1-9]\d*$/.test(value) ? void 0 : "请输入正整数") : void 0);
    },

    /**
     * 展示组件身体
     * @param item
     * @param extraData
     */
    show(item, extraData) {
      this.extraData = extraData;
      this.visible = true;
      // 增加初识状态
      this.list = item.map((i) => ({ ...i, check: false, count: void 0 }));
      // 初始化list集合值
      this.formModel = { list: this.list };
      // 等待渲染后出发table加载
      this.$nextTick(() => this.$refs.table.loadData());
    },

    /**
     * 进行退药操作
     */
    onReturnMedicine() {
      return new Promise((res) => {
        this.$refs.form.validate((pass) => {
          if (pass) {
            // 筛选合法数据
            const list = this.formModel.list.filter((i) => i.check && i.count);
            if (!list.length) {
              res();
              return this.$message.error("请选择并输入要退还的药品数量！");
            }
            // 调用接口前需要将数据转为后端要求的合法请求参数
            this.$api
              .returnMedicine(hackParamsByArray({ ids: list.map((i) => ({ id: i.id, num: i.count })), remark: this.formModel.remark }))
              .then((result) => {
                if (result.success && result.executed) {
                  this.$message.success("药品已退！");
                  this.visible = false;
                  // 触发完成事件给父组件
                  this.$emit("done", this.extraData);
                } else this.$message.error(result.message);
              })
              .finally(res);
          } else res();
        });
      });
    },
  },
};
</script>

<style scoped></style>
